package com.ycl.javacore.algorithm;

/**
 * User: OF1089 杨成龙
 * Date: 2019/8/4
 * Time: 10:25 PM
 * Desc: 反转链表
 */
public class AlgoCast09Link {
    public static class ListNode {
        private int val;
        private ListNode next;

        public ListNode(int val) {
            this.val = val;
        }
    }

    public ListNode reverseList(ListNode head) {
        ListNode pre = null;
        ListNode cur = head;
        while (cur != null) {
            ListNode next = cur.next;//需要先保存当前节点的next指针，因为后面此指针会发生变动，如果不保存的话，那链表就断开了
            cur.next = pre;
            pre = cur;
            cur = next;
        }
        return pre;
    }

    public static void main(String[] args) {
        AlgoCast09Link link = new AlgoCast09Link();

        ListNode node3 = new ListNode(3);
        ListNode node7 = new ListNode(7);
        ListNode node5 = new ListNode(5);

        node3.next = node7;
        node7.next = node5;

        System.out.println(node3.val + "-" + node3.next.val + "-" + node3.next.next.val);

        link.reverseList(node3);

        System.out.println(node5.val + "-" + node5.next.val + "-" + node5.next.next.val);
    }
}
